package com.felix.thread.semaphore;

import java.util.Date;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * SemaphoreDemo
 *
 * @author xuejinhua
 * @date 2018/10/25 15:22
 */
public class SemaphoreDemo {

    private static Semaphore semaphore = new Semaphore(1);
    private static ExecutorService executor = Executors.newFixedThreadPool(7);

    private static void useSemaphore() {
        try {
            semaphore.acquire();
            System.out.println(new Date() + ":获取到信号量");
            Thread.sleep(new Random().nextInt(1000));
            System.out.println(new Date() + ":释放信号量");
            semaphore.release();
        } catch (Exception e) {

        }

    }

    public static class Task implements Runnable {

        @Override
        public void run() {
            useSemaphore();
        }
    }

    public static void main(String[] args) {
        for (int i = 0; i < 7; i++) {
            executor.execute(new Task());
        }
    }

}
